// 显示当前月份 到以后的月份
const date = new Date()
const year = date.getFullYear()
const month = date.getMonth()
const calendarBody = document.querySelector('.calendar--container_body')

// 获取月份具体天数
function getDayInMonth(year, month) {
  return 32 - new Date(year, month, 32).getDate()
}
function generateDayArr(year, month) {
  let days = []
  const totalDay = getDayInMonth(year, month)

  for (let day = 1; day <= totalDay; day++) {
    
    const date = new Date(year, month, day)
    let config = {
      date,
      text: day
    }
    days.push(config)
  }

  return days
}

// 日历中当前月份的每一天
function generatrDivByDayArr(year, month) {
  let days = generateDayArr(year, month)
  let fragment = document.createDocumentFragment()

  for (let i = 0; i < days.length; i++) {
    const div = document.createElement('div')
    div.textContent = days[i].text
    div.style.width = "14.28%"
    div.style.textAlign = "center"
    if (i === 0) {
      const offset = days[i].date.getDay()
      div.style.marginLeft = 14.28 * offset + '%'
    }

    if (days[i].date.toDateString() === date.toDateString()) {
      div.style.background = 'red'
    }
    fragment.appendChild(div)
  }

  return fragment
}

// 生成日历的容器
function generatorDivFrag (fragment) {
  const daysDiv = document.createElement('div')
  daysDiv.style.display = "flex"
  daysDiv.style.flexWrap = 'wrap'
  daysDiv.appendChild(fragment)

  return daysDiv
}

// 日历的标题
function generatorTitleFrag(year, month) {
  let fragment = document.createDocumentFragment()

  const titleDiv = document.createElement('div')
  titleDiv.textContent = `${year}年${month + 1}月`
  titleDiv.style.textAlign = 'center'
  fragment.appendChild(titleDiv)

  return titleDiv
}

function init() {

  let fragment = document.createDocumentFragment()
  let date = new Date()

  for (let i = 0; i < 6; i++) {
    let year = date.getFullYear()
    let month = date.getMonth()

    const daysArr = generatrDivByDayArr(year, month)
    const daysArrFrag = generatorDivFrag(daysArr)
    const titleDiv = generatorTitleFrag(year, month)

    fragment.appendChild(titleDiv)
    fragment.appendChild(daysArrFrag)
    date.setMonth(month + 1)
  } 
  
  calendarBody.appendChild(fragment)

}

init()
